package br.com.obardavez.web.filter;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.logging.Logger;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
@SuppressWarnings("rawtypes")
@Provider
@Produces("application/json")
public class MessageBodyWriterJSON implements MessageBodyWriter{
    Logger log = Logger.getLogger(MessageBodyWriterJSON.class.getName());
 
    @Override
    public long getSize(Object obj, Class type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return -1;
    }
 
    @Override
    public boolean isWriteable(Class type, Type genericType,
            Annotation annotations[], MediaType mediaType) {
         
        //TODO: Come up with our own Annonation class as marker to identify if a class can be serialized using Jackson
        return true;
    }
 
    @Override
    public void writeTo(Object target, Class type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap httpHeaders, OutputStream outputStream)
            throws IOException {
      //  log.info(target.getClass().getName());
 
        ObjectMapper om = new ObjectMapper();
       // StringWriter sw = new StringWriter();
        try {
            om.writeValue(outputStream, target);
        } catch (JsonGenerationException e) {
            log.severe(e.getMessage());
            throw e;
        } catch (JsonMappingException e) {
            log.severe(e.getMessage());
            throw e;
        } catch (IOException e) {
            log.severe(e.getMessage());
            throw e;
        }
    }
}